package server;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import dao.DietDAO;
import dao.UserVO;

public class DietServer {
	
	//public static final String ServerIP = "192.168.43.18"; // ex: 192.168.0.100
	public static final String ServerIP = "10.250.64.182"; // ex: 192.168.0.100
	
    public static void main(String args[]) {
		int port = 6789;
		DietServer server = new DietServer( port );
		server.startServer();
    }

    // declare a server socket and a client socket for the server;
    // declare the number of connections

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int numConnections = 0;
    int port;
	
    public DietServer( int port ) {
    	this.port = port;
    }

    public void stopServer() {
		System.out.println( "Server cleaning up." );
		System.exit(0);
    }

    public void startServer() {
	// Try to open a server socket on the given port
	// Note that we can't choose a port less than 1024 if we are not
	// privileged users (root)
	
        try {
        	echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
        	System.out.println(e);
        }   
	
		System.out.println( "Server is started and is waiting for connections." );
		System.out.println( "With multi-threading, multiple connections are allowed." );
		System.out.println( "Any client can send -1 to stop the server." );

	// Whenever a connection is received, start a new thread to process the connection
	// and wait for the next connection.
	
		while ( true ) {
		    try {
				clientSocket = echoServer.accept();
				numConnections ++;
				Server2Connection oneconnection = new Server2Connection(clientSocket, numConnections, this);
				new Thread(oneconnection).start();
		    }   
		    catch (IOException e) {
		    	System.out.println(e);
		    }
		}
    }
}

class Server2Connection implements Runnable {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    int id;
    DietServer server;

    public Server2Connection(Socket clientSocket, int id, DietServer server) {
		this.clientSocket = clientSocket;
		this.id = id;
		this.server = server;
		System.out.println( "Connection " + id + " established with: " + clientSocket );
		try {
		    is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		    os = new PrintStream(clientSocket.getOutputStream());
		} catch (IOException e) {
		    System.out.println(e);
		}
    }

	public void run() {
        String line;
        List<String> inputData;
        DietDAO dao = null;
        
        // test string
        String name = null;
        String result = null;
        
		try {
		    boolean serverStop = false;
		    inputData = new ArrayList<String>();
		    
            while (true) {
                line = is.readLine();
                System.out.println( "Received " + line + " from Connection " + id + "." );
                
                // Tokenize Input String
                StringTokenizer st = new StringTokenizer(line, ":");
                while(st.hasMoreTokens()) {
                	inputData.add(st.nextToken());
                }
                
                // Manage Received Client Data
                if(inputData.get(0).equals("regist")) {
                	UserVO uv = new UserVO(inputData.get(1), inputData.get(2), inputData.get(3), inputData.get(4));
                	try {
                		dao = new DietDAO();
						dao.add(uv);
					} catch (Exception e) {
						e.printStackTrace();
					}
                }else if(inputData.get(0).equals("isMember")) {
                	System.out.println("IF STATEMENT: isMember" + ", Data: " + inputData.get(1));
                	dao = new DietDAO();
                	try {
//						UserVO uv = new UserVO();
                		String isInDB = null;
						isInDB = dao.find(inputData.get(1));
						
						if(isInDB.equals("TRUE")) {
							result = "TRUE";
						} else {
							result = "FALSE";
						}
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }
                
                // Print to Android Machine
                PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(clientSocket.getOutputStream())),true);
                System.out.println("Server result value is: " + result);
//        		out.println("Server Received "+ line);
                out.println(result);
                
                int n = Integer.parseInt(line);
                if ( n == -1 ) {
                	serverStop = true;
                	break;
                }	
                if ( n == 0 ) break;
	                os.println("" + n*n );
            }
	
	    	System.out.println( "Connection " + id + " closed." );
            is.close();
            os.close();
            clientSocket.close();

		    if ( serverStop ) server.stopServer();
		} catch (IOException e) {
		    System.out.println(e);
		}
    }
}
